package middleware

import (
	"errors"
	"github.com/Kong/go-pdk"
	"go-kong-auth-practice/kong-auth-plugins/model"
)

type RoleHandler struct {
	casbinRoleModel model.CasbinRuleModel
	sysUserModel model.SysUserModel
}

func NewRoleHandler(user,pwd,host,dbName string,port int) *RoleHandler{
	return &RoleHandler{
		casbinRoleModel: model.NewCasbinRuleModel(user,pwd,host,dbName,port),
		sysUserModel: model.NewSysUserModel(user,pwd,host,dbName,port),
	}
}

func (roleHandler *RoleHandler) CasbinHanlder(claims *CustomClaims,kong *pdk.PDK) error{
	user := roleHandler.sysUserModel.SelectByUserId(claims.UserId)
	if user == (model.SysUser{}) {
		return errors.New("token解析失败")
	}
	obj,_ := kong.Request.GetPath()
	// 获取请求方法
	act,_ := kong.Request.GetMethod()
	sub := user.RoleId
	e := roleHandler.casbinRoleModel.Casbin()
	// 判断策略中是否存在
	success, _ := e.Enforce(sub, obj, act)
	if success {
		return nil
	} else {
		return errors.New("token解析失败")
	}
}
